﻿using DataAccess;
using IntelligentQuery.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using DataEntity;

namespace WebUI.Controllers
{
    public class GoodsController : Controller
    {
        //
        // GET: /Goods/
          private DataContext db = new DataContext();
      
        /// <summary>
        /// 物品分类
        /// </summary>
        private IEntityRepository<OffGoodsClass> GoodsClassRepository;

        /// <summary>
        /// 物品
        /// </summary>
        private IEntityRepository<OffGoods> GoodsRepository;
        public GoodsController()
        {
            GoodsRepository = new EntityRepository<OffGoods>(db);
            GoodsClassRepository = new EntityRepository<OffGoodsClass>(db);
        }
        public ActionResult GoodsManageIndex()
        {
            return View();
        }
        public ActionResult GoodsClassManageIndex()
        {
            return View();
        }

        public ActionResult GoodsList(int classid)
        {
            ViewBag.ClassID = classid;
            return PartialView();
        }



        #region  json返回数据
        /// <summary>
        /// 物品信息数据
        /// </summary>
        /// <param name="page"></param>
        /// <param name="rows"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult GoodsJson(int classid,int? page, int? rows, string model)
        {
            int Page = page ?? 1;
            int Rows = rows ?? 10;
            QueryModel QModel = null;
            Dictionary<string, object> JsonObj = new Dictionary<string, object>();
            if (!string.IsNullOrWhiteSpace(model))
            {
                QModel = IntelligentQuery.AjaxQueryConverter.ToQueryModel(model);
            }


            var goods = GoodsRepository.Get(QModel).Where(n=>!n.BeLock&&n.OffGoodsClassID==classid).ToList();

            JsonObj.Add("total", goods.Count());
            JsonObj.Add("rows", goods.OrderByDescending(p => p.ID)
                    .Skip((Page - 1) * Rows)
                   .Take(Rows).Select(s => new { s.ID, s.Name,s.OffGoodsClassID,goodsClassName=s.OffGoodsClass.Name, s.Remark, s.BeLock,s.Inventory,s.AverageAfterTaxPrice,s.SortNumber,s.Unit,s.Des,s.Code }));


            return JsonHelper.JsonEx(JsonObj);
        }
        /// <summary>
        /// 物品类别数据
        /// </summary>
        /// <param name="page"></param>
        /// <param name="rows"></param>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult GoodsClassJson(int? page, int? rows, string model)
        {
            int Page = page ?? 1;
            int Rows = rows ?? 10;
            QueryModel QModel = null;
            Dictionary<string, object> JsonObj = new Dictionary<string, object>();
            if (!string.IsNullOrWhiteSpace(model))
            {
                QModel = IntelligentQuery.AjaxQueryConverter.ToQueryModel(model);
            }


            var goodsClass = GoodsClassRepository.Get(QModel).Where(n => !n.BeLock).ToList();

            JsonObj.Add("total", goodsClass.Count());
            JsonObj.Add("rows", goodsClass.OrderBy(n=>n.SortNumber)
                    .Skip((Page - 1) * Rows)
                   .Take(Rows).Select(s => new { s.ID, s.Name, s.Remark,s.SortNumber,s.BeLock}));


            return JsonHelper.JsonEx(JsonObj);
        }
        #endregion
        #region 操作数据
        /// <summary>
        /// 新建/编辑页
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public ActionResult GoodsCreateEdit(int classid,int id = 0)
        {
            var model = new OffGoods();
            model.OffGoodsClassID = classid;
            if (id != 0)
            {
                model = GoodsRepository.GetByKey(id);
            }
            return PartialView(model);
        }
        /// <summary>
        /// 物品类别新建编辑页面
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public ActionResult GoodsClassCreateEdit(int id = 0)
        {
            var model = new OffGoodsClass();

            if (id != 0)
            {
                model = GoodsClassRepository.GetByKey(id);
            }
            return PartialView(model);
        }
        /// <summary>
        /// 物品保存
        /// </summary>
        /// <param name="role"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult GoodsSave(OffGoods model)
        {
            try
            {

                if (model.ID == 0)
                {

                    GoodsRepository.Insert(model);
                }
                else
                {
                    OffGoods good = GoodsRepository.GetByKey(model.ID);


                    good.Code = model.Code;
                    good.Des = model.Des;
                    good.Name = model.Name;
                    good.OffGoodsClassID = model.OffGoodsClassID;
                   
                    good.Remark = model.Remark;
                    good.SortNumber = model.SortNumber;
                    good.Unit = model.Unit;

                    GoodsRepository.Update(good);

                }


                return Json(new { success = true });
            }
            catch (Exception e)
            {
                return Json(new { msg = e.Message });
            }
        }
        /// <summary>
        /// 物品类别保存
        /// </summary>
        /// <param name="role"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult GoodsClassSave(OffGoodsClass model)
        {
            try
            {

                if (model.ID == 0)
                {

                    GoodsClassRepository.Insert(model);
                }
                else
                {
                    OffGoodsClass goodsClass = GoodsClassRepository.GetByKey(model.ID);


                    goodsClass.Name = model.Name;
                    goodsClass.SortNumber = model.SortNumber;
                    goodsClass.Remark = model.Remark;

                    GoodsClassRepository.Update(goodsClass);

                }


                return Json(new { success = true });
            }
            catch (Exception e)
            {
                return Json(new { msg = e.Message });
            }
        }


        /// <summary>
        /// 单个删除
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public ActionResult GoodsSingleDelete(int id)
        {
            try
            {
                var goods= GoodsRepository.GetByKey(id);
                goods.BeLock = true;
                GoodsRepository.Update(goods);

                return Json(new { success = true });
            }
            catch (Exception e)
            {
                return Json(new { msg = e.Message });
            }
        }

        /// <summary>
        /// 批量删除
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        public ActionResult GoodsBatchDelete(string ids)
        {
            try
            {
                List<string> list_id = ids.Split(',').ToList();
                var GoodsList = GoodsRepository.Get().ToList().Where(u => list_id.Contains(u.ID.ToString())).ToList();
                foreach (var goods in GoodsList)
                {
                    goods.BeLock = true;

                }
                GoodsRepository.Update(GoodsList);
                return Json(new { success = true });
            }
            catch (Exception e)
            {
                return Json(new { msg = e.Message });
            }
        }

        /// <summary>
        /// 单个删除
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public ActionResult GoodsClassSingleDelete(int id)
        {
            try
            {
                var goodsClass = GoodsClassRepository.GetByKey(id);
                goodsClass.BeLock = true;
                GoodsClassRepository.Update(goodsClass);

                return Json(new { success = true });
            }
            catch (Exception e)
            {
                return Json(new { msg = e.Message });
            }
        }

        /// <summary>
        /// 批量删除
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        public ActionResult GoodsClassBatchDelete(string ids)
        {
            try
            {
                List<string> list_id = ids.Split(',').ToList();
                var GoodsClassList = GoodsClassRepository.Get().ToList().Where(u => list_id.Contains(u.ID.ToString())).ToList();
                foreach (var goodsclass in GoodsClassList)
                {
                    goodsclass.BeLock = true;

                }
                GoodsClassRepository.Update(GoodsClassList);
                return Json(new { success = true });
            }
            catch (Exception e)
            {
                return Json(new { msg = e.Message });
            }
        }
        #endregion
        #region 物品类别树
        /// <summary>
        /// 物品类别树数据
        /// </summary>
        /// <returns></returns>
        public ActionResult GoodsClassForTree()
        {
            List<Object> result = new List<Object>();
            var goodsClass=GoodsClassRepository.Get(n=>!n.BeLock).OrderBy(n=>n.SortNumber).ToList();
            foreach (var item in goodsClass)
            {
                result.Add(new { id = item.ID, text = item.Name, iconCls = "icon-menu-goodsclass" });
            }
            return Json(result);
        }

        #endregion

        #region 节点数据
        /// <summary>
        /// 为combobox提供物品数据
        /// </summary>
        /// <returns></returns>

        public ActionResult GoodsJsonForCombobox(int goodsclassid)
        {
            var Good = GoodsRepository.Get(n=>!n.BeLock&&!n.OffGoodsClass.BeLock&&n.OffGoodsClassID==goodsclassid).OrderBy(o => o.SortNumber);

            return Json(Good.Select(s => new { value = s.ID, text = s.Name }));
        }
        /// <summary>
        /// 为combobox提供物品类别数据
        /// </summary>
        /// <returns></returns>
       public ActionResult GoodsClassJsonForCombobox()
        {
            var GoodClass = GoodsClassRepository.Get(n=>!n.BeLock).OrderBy(o => o.SortNumber);

            return Json(GoodClass.Select(s => new { value = s.ID, text = s.Name }));
        }
        /// <summary>
        /// 根据物品ID得到物品计量单位
        /// </summary>
        /// <param name="goodsid"></param>
        /// <returns></returns>
       public string GetGoodsUnit(int goodsid)
       {
           var good = GoodsRepository.GetByKey(goodsid);
           if (good != null)
           {
               return good.Unit;
           }
           else
           {
               return "";
           }
       }
        /// <summary>
        /// 得到库存数量
        /// </summary>
        /// <param name="goodsid"></param>
        /// <returns></returns>
       public int GetGoodsInventory(int goodsid)
       {
           var good = GoodsRepository.GetByKey(goodsid);
           if (good != null)
           {
               return good.Inventory;
           }
           else
           {
               return 0;
           }
       }
       /// <summary>
       /// 得到库存平均价格
       /// </summary>
       /// <param name="goodsid"></param>
       /// <returns></returns>
       public decimal GetGoodsPrice(int goodsid)
       {
           var good = GoodsRepository.GetByKey(goodsid);
           if (good != null)
           {
               return good.AveragePerPrice;
           }
           else
           {
               return 0;
           }
       }
        /// <summary>
        /// 得到库存平均价格
        /// </summary>
        /// <param name="goodsid"></param>
        /// <returns></returns>
       public decimal GetGoodsTaxPrice(int goodsid)
       {
           var good = GoodsRepository.GetByKey(goodsid);
           if (good != null)
           {
               return good.AverageAfterTaxPrice;
           }
           else
           {
               return 0;
           }
       }
        #endregion
        protected override void Dispose(bool disposing)
        {
            db.Dispose();
            base.Dispose(disposing);
        }
    }
}
